<template>
  <div>
    <!--    <h1>角色管理</h1>-->
    <div class="app-container">
      <n-card>
        <div>
          <n-button type="primary" @click="handleAddRole"  v-auth="'system-role-add'">添加角色</n-button>
        </div>
        <n-data-table class="m-t-10" size="small" :columns="columns" :data="tableData"
                      :single-line="false"></n-data-table>
        <pagination :total="total" :getList="getList"/>
      </n-card>
    </div>
    <c-modal @register="modalRegister" @on-ok="handleSubmit" style="width: 600px"
             :title="`${ isCreate ? '添加' : '编辑' }系统角色`">
      <n-card>
        <n-form
            label-width="100"
            label-align="left"
            class="m-t-20"
            :model="form"
            :rules="formRules"
            ref="formRef"
            label-placement="left">
          <n-form-item label="角色名称:" path="label">
            <n-input placeholder="请输入角色名称" v-model:value="form.label"/>
          </n-form-item>
          <n-form-item label="角色描述:" path="describe">
            <n-input placeholder="请输入角色描述" v-model:value="form.describe"/>
          </n-form-item>
          <n-form-item label="角色菜单权限:">
            <n-card style="height: 200px;overflow-y: scroll">
              <n-tree
                  style="width: 300px;"
                  block-line
                  cascade
                  checkable
                  :data="menuTrees"
                  :check-strategy="'child'"
                  :default-expanded-keys="form.menuIds"
                  :default-checked-keys="form.menuIds"
                  @update:checked-keys="handleSelectMenu"
              />
            </n-card>
          </n-form-item>
          <n-form-item label="角色状态:" path="status">
            <n-radio-group v-model:value="form.status">
              <n-space>
                <n-radio :value="1101">启用</n-radio>
                <n-radio :value="1102">禁用</n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>
        </n-form>
      </n-card>
    </c-modal>
  </div>
</template>

<script setup lang="ts">
import { tableColumns, formRules, baseForm, FormType } from './data/role'
import { CModal, useModal } from '../../components/Modal'
import { useConfirm } from "../../components/confirm";
import { reactive, Ref, ref } from "vue";
import { apiMenuAll } from "../../api/system/menu";
import { formatMenu } from "./data/menu";
import { isEmpty } from '../../utils/is';
import { syncValidate } from "../../utils/common";
import { useMessage } from 'naive-ui'
import { usePagination } from "../../components/pagination";
const { confirmWarning } = useConfirm()
const message = useMessage();
import { apiAddRole, apiRolePage, apiRoleDetail, apiUpdateRole, apiRoleDelete } from "../../api/system/role";
import { PageType } from "../../types/global";

/** 初始化表格数据 */
const columns = tableColumns({
  // 编辑
  updateFn: async (row: any) => {
    const { data } = await apiRoleDetail(row.id);
    data['menuIds'] = data.menus.filter((item: any) => item.type == 1103).map((item: any) => item.id);
    isCreate.value = false;
    openModal();
    form.value = data;
  },
  // 删除
  deleteFn: async (row: any) => {
    await confirmWarning();
    await apiRoleDelete([row.id])
    message.success('删除成功');
    await getList()
  }
})

/** 获取角色列表 */
let tableData: Ref<Array<FormType>> = ref([])
let total: Ref<number> = ref(0);
// 把getList放在分页组件里面调用，并且使用闭包记录当前分页，有助于在当前页面直接获取当前分页，不需要子组件传递过来
const { initGetList } = usePagination()
let getList = initGetList(async (pageData) => {
  let { data } = await apiRolePage(pageData as PageType);
  tableData.value = data.rows;
  total.value = data.count;
})
getList();

/** 获取菜单列表 */
let menuTrees: Ref<any[]> = ref([])
async function getMenuTree() {
  const { menusList } = await apiMenuAll();
  menuTrees.value = formatMenu(menusList);
}
getMenuTree();

/** 添加，编辑角色 */
const form: Ref<FormType> = ref(baseForm())
let formRef: any = ref()
let isCreate: Ref<boolean> = ref(false)

const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({});

function handleAddRole() {
  isCreate.value = true;
  form.value = baseForm();
  openModal();
}

/** 选择菜单 */
function handleSelectMenu(menuIds: []) {
  form.value.menuIds = menuIds;
}

async function handleSubmit(e: Event) {
  e.preventDefault()
  try {
    await syncValidate(formRef)
    if (isEmpty(form.value.menuIds)) {
      message.warning('请选择菜单权限');
      return;
    } else {
      if (isCreate.value) {
        await apiAddRole(form.value);
      } else {
        await apiUpdateRole(form.value);
      }
      message.success(`${ isCreate.value ? '添加' : '更新' }成功`);
      setSubLoading(false);
      closeModal();
      await getList()
    }
  } catch (e) {
    // message.warning('请正确填写信息');
    setSubLoading(false)
  }
}

</script>

<style scoped>

</style>
